package com.shadowlight.hero_story;

import com.google.protobuf.GeneratedMessageV3;
import com.shadowlight.hero_story.msg.GameMsgProtocol;
import com.shadowlight.hero_story.pojo.UserRepository;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class GameMsgHandler extends SimpleChannelInboundHandler<Object> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        Broadcaster.addChannel(ctx.channel());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        super.handlerRemoved(ctx);

        Integer userId = (Integer) ctx.channel().attr(AttributeKey.valueOf("userId")).get();
        if (userId == null) return;
        UserRepository.getInstance().removeUserById(userId);
        //发指令给前端，删除掉离线的人
        GameMsgProtocol.UserQuitResult.Builder userQuitResultBuilder = GameMsgProtocol.UserQuitResult.newBuilder();
        userQuitResultBuilder.setQuitUserId(userId);
        Broadcaster.removeChannel(ctx.channel());
        Broadcaster.broadcast(userQuitResultBuilder.build());
    }

    @Override
    protected void messageReceived(ChannelHandlerContext channelHandlerContext, Object msg) {
        log.debug("服务器接收到消息, msgClazz = {}, msg = {}", msg.getClass().getName(), msg);

        if (msg instanceof GeneratedMessageV3) {
            MainThreadProcessor.getInstance().process(channelHandlerContext, msg);
        }
    }
}
